package com.yang.lay.system.controller;

import com.yang.lay.core.captcha.Captcha;
import com.yang.lay.core.captcha.GifCaptcha;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class KaptchaController {
    @RequestMapping("/image/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response)
            throws  IOException {
        //获取codeKey
        String codeKey = request.getParameter("codeKey");
        if (codeKey == null || codeKey.trim().isEmpty()) {
            return;
        }

        //设置输出图片
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // gif验证码, 宽、高、位数
        Captcha captcha = new GifCaptcha(130, 38, 5);
        // 存入servletContext
        ServletContext servletContext = request.getSession().getServletContext();
        servletContext.setAttribute("code_" + codeKey, captcha.text().toLowerCase());

        //输出图片
        captcha.out(response.getOutputStream());
    }
}
